let currentEditingId = null; // 当前正在编辑的学生ID

document.addEventListener('DOMContentLoaded', function() {
    populateStudentsTable();
    document.getElementById('studentForm').addEventListener('submit', handleFormSubmit);
});

function populateStudentsTable() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost:3000/students', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const students = JSON.parse(xhr.responseText);
            const tableBody = document.querySelector('#studentsTable tbody');
            tableBody.innerHTML = '';
            students.forEach(student => {
                const row = tableBody.insertRow();
                row.insertCell(0).textContent = student.name;
                row.insertCell(1).textContent = student.age;
                row.insertCell(2).textContent = student.major;
                row.insertCell(3).textContent = student.grade;
                const actionCell = row.insertCell(4);
                const editButton = document.createElement('button');
                editButton.textContent = '修改';
                editButton.onclick = function() { showEditForm(student); };
                const deleteButton = document.createElement('button');
                deleteButton.textContent = '删除';
                deleteButton.onclick = function() { deleteStudent(student.id); };
                actionCell.appendChild(editButton);
                actionCell.appendChild(deleteButton);
            });
        }
    };
    xhr.send();
}

function handleFormSubmit(event) {
    event.preventDefault();
    const studentData = {
        name: document.getElementById('name').value,
        age: document.getElementById('age').value,
        major: document.getElementById('major').value,
        grade: document.getElementById('grade').value
    };

    if (currentEditingId) {
        updateStudent(currentEditingId, studentData);
    } else {
        addStudent(studentData);
    }
}

function addStudent(studentData) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://localhost:3000/students', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 201) {
            populateStudentsTable();
            document.getElementById('studentForm').reset();
        }
    };
    xhr.send(JSON.stringify(studentData));
}

function deleteStudent(id) {
    const xhr = new XMLHttpRequest();
    xhr.open('DELETE', `http://localhost:3000/students/${id}`, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            populateStudentsTable();
        }
    };
    xhr.send();
}

function showEditForm(student) {
    const form = document.getElementById('studentForm');
    form.querySelector('input[name="name"]').value = student.name;
    form.querySelector('input[name="age"]').value = student.age;
    form.querySelector('input[name="major"]').value = student.major;
    form.querySelector('input[name="grade"]').value = student.grade;
    form.querySelector('button[type="submit"]').textContent = '更新';
    currentEditingId = student.id; // 设置当前编辑的学生ID
}

function updateStudent(id, studentData) {
    const xhr = new XMLHttpRequest();
    xhr.open('PUT', `http://localhost:3000/students/${id}`, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            populateStudentsTable();
            document.getElementById('studentForm').reset();
            document.getElementById('studentForm').querySelector('button[type="submit"]').textContent = '添加学生';
            currentEditingId = null; // 清空当前编辑的学生ID
        }
    };
    xhr.send(JSON.stringify(studentData));
}